<?php
if( !APP_ROOT )
    return 'Direct Access Deny!';
    
use libraries\Verify;
use libraries\Benchmark;
use libraries\RQueue;
use libraries\RedisSession;
use enums\HttpServerEnums;
use libraries\CommUtils;
use libraries\RedLock;
use ephalcon\http\EResponse;
// use ephalcon\http\response\CookiesSwoole;

$config = $di['config'];

// $di->set( 'mongodb', function (){
    
//     $mongo =  new \MongoClient( '192.168.1.126:27017' );
    
//     return $mongo->selectDB( 'imgs' );
        
// }, true );

	
$di->set( 'logger', function(){
	
	$logger = new \Phalcon\Logger\Adapter\File( APP_ROOT . "logs/php_error_log.txt");
	
	return $logger;
	
}, true );


$di->set( 'bm', function(){
    
    $bm = new Benchmark();
    return $bm;
    
}, true );

if( CommUtils::getServerType() == HttpServerEnums::SERVER_TYPE_SWOOLE )
{
	$di->set( 'response', function(){
		include_once APP_ROOT . '/ephalcon/http/EResponse.php';
		$response = new \ephalcon\http\EResponse();
		return $response;
	}, true );
}

$di->set( 'cookies', function()
{
	if( CommUtils::getServerType() == HttpServerEnums::SERVER_TYPE_COMMON )
	{
		$cookies = new \Phalcon\Http\Response\Cookies();
	}
	else
	{
		include_once APP_ROOT . 'ephalcon/http/response/CookiesSwoole.php';
		
		$cookies = new \ephalcon\http\response\CookiesSwoole();
		$cookies->setDI( $this );
	}

	$cookies->useEncryption( false );
	
	//  	ini_set( 'session.cookie_path', 1 );
	return $cookies;
});
	
	
$di->set( 'session', function() use( $config ) {
    
    if( !extension_loaded( 'redis' ))
    {
        return 'redis extension not loaded!<br>';
    }
    
    ini_set( 'session.name', HttpServerEnums::SESSION_KEY );
    ini_set( 'session.cookie_httponly', 1 );
    
    if( CommUtils::getServerType() == HttpServerEnums::SERVER_TYPE_COMMON )
    {
    	$session = new \Phalcon\Session\Adapter\Redis([
	        'uniqueId' => 'mobile',
	        'host' => '127.0.0.1',
	        'port' => 6379,
	        //'auth' => 'foobared',
	        //'persistent' => false,
	        'lifetime' => 3600,
	        'prefix' => 'mobile_',
	        'index' => 0,
    	]);
    	$session->start();
    }
    else
    {
		$redis = new \Redis();
    	$redis->connect( '127.0.0.1', 6379 );
    	$redis->select( 0 );
    	
    	include_once APP_ROOT . 'ephalcon/session/adapter/RedisSession.php';
    	
    	$this->redisSessionServer = $redis;
    	
    	$option = array( 'lifetime' => 3600, 'fetchMode' => 0 );
    	$session = new ephalcon\session\adapter\RedisSession( $this, $option );
    }
    
    return $session;
}, true );


$di->set( 'crypt', function(){
	$crypt = new \phalcon\Crypt();
	$crypt->setKey('#1dj8$=dp?.ak//j1V$asdf'); // Use your own key!
	return $crypt;
});

// Registering a router
$di->set( 'router',function () {
    
    require_once APP_ROOT . 'config/router.php';
    return $router;
}, true );

// Registering unitTest
$di->set( 'utest', function () {
    
    return new \libraries\UnitTest();
    
}, true );

$di->set( 'url', function () use ( $config ) {
    
    $url = new Phalcon\Mvc\Url();
    $url->setBaseUri( $config->application->baseUri );
    return $url;
    
}, true );

// 验证码
$di->set( 'verify', function () {
    
    $verify = new Verify();
    $verify->setDI( $this );
    return $verify;
    
}, true );

// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// cache
/**
 * for html segment
 */
$di->set( 'htmlCache',  function () use ( $config ) {

    if( !file_exists( $config->application->cacheDir . 'html/' ) && !mkdir( $config->application->cacheDir . 'html/' ) )
    {
        var_dump( error_get_last() );
        return;
    }

    $frontCache = new \Phalcon\Cache\FrontEnd\Output( $config->cache->htmlCache->frontend ); // cache two days
    $cache = new \Phalcon\Cache\Backend\File( $frontCache, $config->cache->htmlCache->backend->toArray() );
    return $cache;
    
}, true );


/**
 * memcache cache
 */
// $di->set( 'memCache', function () use ( $config ) {
    
//    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->memcache->frontend->toArray() ); // cache two days
//    if( !extension_loaded( 'memcache' ) )
//    {
//        return 'memcache extension not loaded!<br>';
//    }
//    else
//    {
//        $cache = new \Phalcon\Cache\Backend\Memcache( $frontCache, $config->cache->memcache->backend->toArray() );
//    }
//    return $cache;
// }, true );

// $di->set( 'memCached', function() use ( $config ){
    
//    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->memcached->frontend ); // cache two days
//    if( !extension_loaded( 'memcached' ) )
//    {
//        return 'memcache extension not loaded!<br>';
//    }
//    else
//    {
//         $cache = new \Phalcon\Cache\Backend\Libmemcached( $frontCache, array( 'servers' => $config->cache->memcached->backend->toArray() ));
//    }
//     return $cache;
// }, true );

/**
 * apc cache
 */
$di->set( 'apcCache', function () use ( $config ) {
    
    if( !extension_loaded( 'apc' ) )
    {
        return 'apc extension not loaded!<br>';
    }

    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->apc->frontend->toArray() ); // cache two days
    $cache = new \Phalcon\Cache\Backend\Apc( $frontCache, $config->cache->apc->backend->toArray() );

    return $cache;
    
}, true );

/**
 * memory 易失性 不能进行序列化 只能在一次请求中有效
 */
$di->set( 'memory', function () use ( $config ) {
    
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->inmem->frontend );
    $cache = new \Phalcon\Cache\Backend\Memory( $frontCache );

    return $cache;
}, true );


// /**
//  * mongodb Cache
//  */
// $di->set( 'mongoCache', function () use ( $config ) {
    
//     if( !extension_loaded( 'mongo' ) )
//     {
//         return 'mongo extension not loaded!';
//     }

//     $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->mongodb->frontend );
//     $cache = new \Phalcon\Cache\Backend\Mongo( $frontCache, $config->cache->mongodb->backend->toArray() );

//     return $cache;
// }, true );


/**
 * redis cache
 */
$di->set( 'redisCache',  function() use ( $config ) {
    
    if( !extension_loaded( 'redis' ))
    {
        return 'redis extension not loaded!<br>';
    }
    
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $config->cache->redisCache->frontend );
    $cache = new \Phalcon\Cache\Backend\Redis( $frontCache, $config->cache->redisCache->backend->toArray() );

    return $cache;
}, true );

/**
 * native redis
 * 原生native使用phpredis扩展
 */
$di->set( 'nredis', function() {
    
	if( !extension_loaded( 'redis' ))
	{
		return 'redis extension not loaded!<br>';
	}
	
	$redis = new \Redis();
	$redis->connect( '192.168.1.254', 6379 /*, 'password'*/ );
	return $redis;
}, true );

$di->set( 'rqueue', function(){
    
	if( !extension_loaded( 'redis' ))
	{
		return 'redis extension not loaded!<br>';
	}
	
	$redis = new \Redis();

	$config = include APP_ROOT . 'config/queue.php';
	
	$redis->connect( $config->server->host, $config->server->port /*, 'password'*/ );
	$redis->select( $config->server->db );
	
	$rq = new RQueue();
	$rq->setConfig( $config );
	$rq->setServer( $redis );
	
	return $rq;
}, true );

/**

/**
 * safe Cache
 * 主要用来生产用 不用
 */
// $di->set( 'safeCache',function () use ( $config ) {
    
//     $frontCache = new \Phalcon\Cache\FrontEnd\Data( array(
//         'lifetime' => 172800
//     ) ); // cache two days

//   if( extension_loaded( 'memcached' ) )
//     {
//         $cache = new \Phalcon\Cache\Backend\Libmemcached($frontCache,  array(  'servers' => $config->cache->memcached->backend->toArray() ) );
//     }
//     else if( extension_loaded( 'memcache' ) )
//     {
//         $cache = new \Phalcon\Cache\Backend\Memcache( $frontCache, $config->cache->memcache->backend->toArray() );
//     }
//     else if( !file_exists( $config->application->cacheDir . 'fileCache/' ) && !mkdir( $config->application->cacheDir . 'fileCache/' ) )
//     {
//         var_dump( error_get_last() );
//         return;
//     }
//     else 
//     {
//         $cache = new \Phalcon\Cache\Backend\File( $frontCache,array(
//             'cacheDir' => $config->application->cacheDir . 'fileCache/'
//         ) );
//     }

//     return $cache;
// }, true );


//-----------------------------------------
// email service
//-----------------------------------------
$di->set( 'email', function() {
    
 //include APP_ROOT . 'config/' . 'email.php'   
    $email = new \libraries\Email();

    return $email;
}, true );


//-----------------------------------------
// lock service
//-----------------------------------------
$di->set( 'redLock', function() use( $di ){
    return new RedLock( $di[ 'nredis' ] );
} );


$di->set( 'modelsMetadata',function(){ 
    
	$metaData = new \Phalcon\Mvc\Model\MetaData\Memory( array(
		'lifetime' => 1440,
	    'prefix' => 'metadata_'
	));
	return $metaData;
}, true );

// $di->set( 'queue', function(){
    
// 	$queue = new \Phalcon\Queue\Beanstalk( $this->config->beanstalk->toArray() );
// 	return $queue;
// }, true );
